package com.qiaofang.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.qiaofang.common.constant.CommonResponseType;
import com.qiaofang.common.constant.ExceptionEnum;
import com.qiaofang.common.exception.BusinessException;
import com.qiaofang.common.model.PageDTO;
import com.qiaofang.common.model.UiListBean;
import com.qiaofang.common.response.CommonResponse;
import com.qiaofang.common.utils.SMSUtil;
import com.qiaofang.dto.ListSmsHistoryDTO;
import com.qiaofang.dto.SmsHistoryDTO;
import com.qiaofang.entity.SmsHistory;
import com.qiaofang.entity.enums.SendStatusEnum;
import com.qiaofang.mapper.SmsHistoryMapper;
import com.qiaofang.repository.SmsHistoryRepository;
import com.qiaofang.service.SmsHistoryService;
import com.qiaofang.vo.SmsHistoryVO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Map;

@Service
public class SmsHistoryServiceImpl implements SmsHistoryService {


    @Autowired
    SmsHistoryMapper smsHistoryMapper;
    @Autowired
    SmsHistoryRepository smsHistoryRepository;
    @Autowired
    SMSUtil smsUtil;

    @Override
    public UiListBean listSmsHistorySummary(ListSmsHistoryDTO dto) {
        UiListBean<SmsHistoryVO> uiListBean = new UiListBean();
        SmsHistoryDTO smsHistoryDTO = new SmsHistoryDTO();
        smsHistoryDTO.setCompanyName(dto.getCompanyName());
        smsHistoryDTO.setCreateTimeStart(dto.getCreateTimeStart());
        smsHistoryDTO.setCreateTimeEnd(dto.getCreateTimeEnd());
        List<SmsHistory> smsHistoryList = smsHistoryMapper.listSmsHistorySummary(smsHistoryDTO);
        List<SmsHistoryVO> voList = new ArrayList<>();
        if(null == smsHistoryList || smsHistoryList.size() == 0){
            return uiListBean;
        }
        for(SmsHistory smsHistory: smsHistoryList){
            SmsHistoryVO vo = new SmsHistoryVO();
            vo.setMerchantId(String.valueOf(smsHistory.getMerchantId()));
            vo.setCompanyName(smsHistory.getCompanyName());
            vo.setSendCount(smsHistory.getSendCount());
            voList.add(vo);
        }
        uiListBean.setList(voList);
        return uiListBean;
    }

    @Override
    public UiListBean listSmsHistoryFailure(ListSmsHistoryDTO dto, PageDTO page) {
        UiListBean<SmsHistoryVO> uiListBean = new UiListBean();
        SmsHistoryDTO smsHistoryDTO = new SmsHistoryDTO();
        smsHistoryDTO.setCompanyName(dto.getCompanyName());
        smsHistoryDTO.setContent(dto.getContent());
        smsHistoryDTO.setCreateTimeStart(dto.getCreateTimeStart());
        smsHistoryDTO.setCreateTimeEnd(dto.getCreateTimeEnd());
        List<SmsHistory> smsHistoryList = smsHistoryMapper.listSmsHistoryFailure(smsHistoryDTO, page);
        List<SmsHistoryVO> voList = new ArrayList<>();
        if(null == smsHistoryList || smsHistoryList.size() == 0){
            return uiListBean;
        }
        for(SmsHistory smsHistory: smsHistoryList){
            SmsHistoryVO vo = new SmsHistoryVO();
            vo.setId(smsHistory.getId());
            vo.setCompanyName(smsHistory.getCompanyName());
            vo.setReceiver(smsHistory.getReceiver());
            vo.setSendStatus(smsHistory.getSendStatus());
            vo.setContent(smsHistory.getContent());
            vo.setCreateTime(smsHistory.getCreateTime());
            voList.add(vo);
        }
        uiListBean.setList(voList);
        uiListBean.setTotalCount(smsHistoryMapper.listSmsHistoryFailureCount(smsHistoryDTO));
        return uiListBean;
    }

    @Override
    public CommonResponse sendFailureSmsAgain(Long id) {
        CommonResponse response = new CommonResponse();
        SmsHistory history = smsHistoryRepository.findById(id).orElseThrow(() -> new BusinessException(ExceptionEnum.NOT_FIND_DB_DATA));
        String repeatCount = history.getRepeatCount();
        String repeatStatus = history.getRepeatStatus() == null ?"0":history.getRepeatStatus();
        int currRepeatCount = 0;
        if(StringUtils.isNotBlank(repeatCount)){
            currRepeatCount = Integer.parseInt(repeatCount);
            if("1".equals(repeatStatus) || null != history.getOriginalId()){
                //代表发送次数过多,不予处理
                response.setResponseMessage("发送次数过多!");
                response.setResponseType(CommonResponseType.ERROR.toString());
                return response;
            }
        }
        currRepeatCount += 1;
        //發送短信.采用第一信息的通道进行补发
        //原因: 没有好用的且有钱的通道.
        Map<String, Object> returnMap = smsUtil.sendMessage(history.getContent(), history.getReceiver(), null, null, null);
        boolean sendStatus = (Boolean) returnMap.get("sendStatus");
        String sendRes = String.valueOf(returnMap.get("sendRes"));

        //保存短信历史信息
        SmsHistory smsHis = new SmsHistory();
        smsHis.setSender(smsUtil.getUserName());
        smsHis.setSender("qiaofang");
        smsHis.setReceiver(history.getReceiver());
        smsHis.setContent(history.getContent());
        smsHis.setSendStatus(sendStatus? SendStatusEnum.SUCCESS.getNo():SendStatusEnum.FAILURE.getNo());
        smsHis.setSendRes(sendRes);
        smsHis.setOriginalId(history.getId());
        smsHis.setRepeatCount(String.valueOf(currRepeatCount));
        smsHis.setMerchantId(history.getMerchantId());
        smsHis.setRemark(history.getRemark());
        smsHis.setCreateUserId(history.getCreateUserId());
        if(returnMap.containsKey("orderUuid")){
            history.setOrderUuid(String.valueOf(returnMap.get("orderUuid")));
        }
        if(returnMap.containsKey("platform")){
            smsHis.setPlatform(String.valueOf(returnMap.get("platform")));
        }
        smsHis.setCreateTime(Calendar.getInstance().getTime());
        smsHistoryRepository.save(smsHis);

        //修改当前短信发送次数
        history.setRepeatStatus(sendStatus?SendStatusEnum.SUCCESS.getNo():SendStatusEnum.FAILURE.getNo());
        history.setRepeatCount(String.valueOf(currRepeatCount));
        smsHistoryRepository.save(history);

        response.setResponseMessage("补发情况: " + sendRes);
        return response;
    }
}
